<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion">后台管理</i>
      </el-breadcrumb-item>
      <el-breadcrumb-item>类别列表</el-breadcrumb-item>
      <el-breadcrumb-item v-for="item in history" v-bind:key="item.name"><span v-text="item.name"></span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" align="center" width="60"></el-table-column>
      <el-table-column prop="name" label="名称" header-align="center" width="180"></el-table-column>
      <el-table-column prop="keywords" label="关键词列表" header-align="center"></el-table-column>
      <el-table-column prop="sort" label="排序序号" align="center" width="80"></el-table-column>
      <el-table-column prop="enable" label="是否启用" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            @change="toggleEnable(scope.row)"
            v-model="scope.row.enable"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ccc"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="isDisplay" label="显示在导航栏" align="center" width="120">
        <template slot-scope="scope">
          <el-switch
            @change="toggleDisplay(scope.row)"
            v-model="scope.row.isDisplay"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ccc"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="子类级别" align="center" width="100">
        <template slot-scope="scope">
          <el-button size="mini" :disabled="scope.row.isParent == 0" @click="showSubCategories(scope.row)">查看 </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="openEditDialog(scope.row)" circle icon="el-icon-edit"></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="openDeleteConfirm(scope.row)"
            circle
            :disabled="scope.row.isParent == 1"
            icon="el-icon-delete"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px" v-if="this.history.length > 0">
      <el-button style="float: right" @click="goback()">返回</el-button>
    </div>

    <!-- 弹出的编辑类别的对话框 -->
    <el-dialog title="修改类别" :visible.sync="dialogFormVisible">
      <el-form :model="editForm">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="关键词列表" :label-width="formLabelWidth">
          <el-input v-model="editForm.keywords" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" :label-width="formLabelWidth">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm()">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      history: [],
      currentParentId: 0,
      tableData: [],
      dialogFormVisible: false,
      editForm: {
        id: "",
        name: "",
        keywords: "",
        sort: "",
      },
      formLabelWidth: "120px",
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    goback() {
      let parentCategory = this.history[this.history.length - 1];
      this.history.pop();
      this.currentParentId = parentCategory.parentId;
      this.loadCategoryList();
    },
    showSubCategories(category) {
      this.history[category.depth - 1] = category;
      this.currentParentId = category.id;
      this.loadCategoryList();
    },
    toggleEnable(category) {
      let enableText = ["禁用", "启用"];
      let url = "http://localhost:8088/categories/" + category.id;
      if (category.enable == 1) {
        url += "/enable";
      } else {
        url += "/disable";
      }
      console.log("url = " + url);
      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .post(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            let message = "操作成功，已经将【" + category.name + "】状态更改为【" + enableText[category.enable] + "】！";
            this.$message({
              message: message,
              type: "success",
            });
          } else {
            this.$message.error(responseBody.message);
            this.loadCategoryList();
          }
        });
    },
    openEditDialog(category) {
      let url = "http://localhost:8088/categories/" + category.id;
      console.log("url = " + url);

      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .get(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.editForm = responseBody.data;
            this.dialogFormVisible = true;
          } else {
            this.$alert(responseBody.message, "警告", {
              confirmButtonText: "确定",
              callback: (action) => {
                this.loadCategoryList();
              },
            });
          }
        });
    },
    openDeleteConfirm(category) {
      let message = "此操作将永久删除【" + category.name + "】类别，是否继续？";
      this.$confirm(message, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.handleDelete(category);
        })
        .catch(() => {});
    },
    handleDelete(category) {
      let url = "http://localhost:8088/categories/" + category.id + "/delete";
      console.log("url = " + url);

      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .post(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.$message({
              message: "删除成功！",
              type: "success",
            });
            this.loadCategoryList();
          } else if (responseBody.state == 40400) {
            this.$alert(responseBody.message, "警告", {
              confirmButtonText: "确定",
              callback: (action) => {
                this.loadCategoryList();
              },
            });
          } else {
            this.$message.error(responseBody.message);
          }
        });
    },
    loadCategoryList() {
      let url = "http://localhost:8088/categories/list-by-parent?parentId=" + this.currentParentId;
      console.log("url = " + url);

      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .get(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.tableData = responseBody.data;
          }
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {},
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
    this.loadCategoryList();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
